#! /usr/bin/env python
# -*- coding: utf-8 -*-

# *************************************************************
#  Copyright (c) JoinQuant Development Team
#
#  Author: Huayong Kuang <kuanghuayong@joinquant.com>
#  CreateTime: 2017-11-23 16:10:59 Thursday
# *************************************************************

import os
import logging


def init_log(log_path, module_name):
    """
    初始化日志模块
    :param log_path 日志的路径
    :param module_name 日志的模块名称
    """
    logging.basicConfig(level=logging.INFO,
                        format="%(asctime)s [" + module_name +
                        " - %(levelname)s] %(message)s",
                        filemode="a",
                        filename=log_path)
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter(
        "%(asctime)s [" + module_name + " - %(levelname)s] %(message)s")
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    if os.path.exists(log_path):
        file_lines = None
        with open(log_path, "r") as f:
            file_lines = f.readlines()
        # 默认保留200万条
        max_log_lines_count = 2000000
        if len(file_lines) > max_log_lines_count:
            file_lines = file_lines[-max_log_lines_count:]
            with open(log_path, "w") as f:
                f.write("".join(file_lines))
                logging.info("将对文件进行截断，只保留后%s条" % max_log_lines_count)


if __name__ == "__main__":
    init_log("test.log", "test")
    logging.info("hello")
    logging.error("error")
